#ifndef XLCOMM_NET_ACCEPTOR_H_
#define XLCOMM_NET_ACCEPTOR_H_

#include <functional>

#include "xlcomm/net/detail/channel.h"
#include "xlcomm/net/detail/socket.h"
#include "xlcomm/net/event_loop.h"
#include "xlcomm/net/inet_address.h"
#include "xlcomm/noncopyable.h"

namespace xlcomm {
namespace net {

// 接受客户端连接
class Acceptor : noncopyable {
 public:
  using NewConnectionCallback =
      std::function<void(int sockfd, const InetAddress& addr)>;

  Acceptor(EventLoop* loop, const InetAddress& listen_addr, bool reuse_port);
  ~Acceptor();

  // 设置新连接回调函数
  void SetNewConnectionCallback(const NewConnectionCallback& cb) {
    new_connection_callback_ = cb;
  }

  // 监听新连接
  void Listen();

  bool listening() const { return listening_; }

 private:
  // 处理accept fd可读事件
  void HandleRead();

  EventLoop* loop_;
  Socket accept_socket_;
  Channel accept_channel_;
  NewConnectionCallback new_connection_callback_;
  bool listening_;
  int idle_fd_;
};

}  // namespace net
}  // namespace xlcomm

#endif  // XLCOMM_NET_ACCEPTOR_H_